/*
@file: SignalSuffixManager.cpp
@author: ZZH
@date: 2023-02-24
@info: 信号名后缀管理器
*/
#include "SignalSuffixManager.h"

SignalSuffixManager::SignalSuffixManager(const size_t bits)
{
    this->numOfCell = bits / this->bitsPerCell + 1;
    this->pMem = new uint32_t[this->numOfCell];
    std::memset(this->pMem, 0, sizeof(uint32_t) * this->numOfCell);
}

SignalSuffixManager::SignalSuffixManager(const SignalSuffixManager& other)
    : SignalSuffixManager(other.numOfCell * other.bitsPerCell)
{
    memcpy(this->pMem, other.pMem, this->numOfCell);
}

bool SignalSuffixManager::get(const size_t bitPos) const
{
    if (nullptr == this->pMem)
        return false;

    size_t bytePos = bitPos / this->bitsPerCell;
    size_t bitOffset = bitPos % this->bitsPerCell;

    if (bytePos > this->numOfCell)
        return false;

    return this->pMem[bytePos] & (1 << bitOffset);
}

void SignalSuffixManager::set(const size_t bitPos, const bool value)
{
    if (nullptr == this->pMem)
        return;

    size_t bytePos = bitPos / this->bitsPerCell;
    size_t bitOffset = bitPos % this->bitsPerCell;

    if (bytePos > this->numOfCell)
        return;

    if (true == value)
        this->pMem[bytePos] |= (1 << bitOffset);
    else
        this->pMem[bytePos] &= ~(1 << bitOffset);
}

size_t SignalSuffixManager::findFirst(const bool val) const
{
    if (nullptr == this->pMem)
        return 0;

    const uint32_t value = UINT32_MAX * (false == val);

    for (size_t i = 0; i < this->numOfCell; i++) {
        if (value != this->pMem[i]) {
            for (size_t j = 0; j < this->bitsPerCell; j++) {
                uint32_t bitMask = 1 << j;
                if (val == ((this->pMem[i] & bitMask) == bitMask))
                    return i * this->bitsPerCell + j;
            }
        }
    }

    return 0;
}
